package com.vcc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.vcc.core.exception.NotFoundException;
import com.vcc.core.exception.ProgramException;
import com.vcc.core.util.RegexUtil;
import com.vcc.data.entity.EnterpriseCertInfo;
import com.vcc.data.mapper.EnterpriseCertInfoMapper;
import com.vcc.service.boss.request.kyc.AuditKycDto;
import com.vcc.service.client.vo.kyc.kyb.EnterpriseCertInfoVo;
import com.vcc.service.sa.BossUserUtil;
import com.vcc.service.service.EnterpriseBeneficiaryService;
import com.vcc.service.service.EnterpriseCertInfoService;
import com.vcc.service.service.EnterpriseManagerService;
import com.vcc.service.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.vcc.data.entity.table.BossUserTableDef.BOSS_USER;
import static com.vcc.data.entity.table.EnterpriseCertInfoTableDef.ENTERPRISE_CERT_INFO;
import static com.vcc.data.entity.table.UserTableDef.USER;

@Service
public class EnterpriseCertInfoServiceImpl extends ServiceImpl<EnterpriseCertInfoMapper, EnterpriseCertInfo> implements EnterpriseCertInfoService {

    @Autowired
    private UserService userService;

    @Resource
    private EnterpriseBeneficiaryService enterpriseBeneficiaryService;
    @Resource
    private EnterpriseManagerService enterpriseManagerService;

    @Override
    public EnterpriseCertInfoVo getById(Long id) {
        EnterpriseCertInfo enterpriseCertInfo = mapper.selectOneWithRelationsByQuery(
                queryChain()
                        .eq(EnterpriseCertInfo::getId, id)
        );
        if (enterpriseCertInfo == null) {
            throw new NotFoundException("没有提交认证信息");
        }
        return BeanUtil.copyProperties(enterpriseCertInfo, EnterpriseCertInfoVo.class);
    }

    @Override
    public EnterpriseCertInfo getByUserId(Long userId) {
        return queryChain()
                .eq(EnterpriseCertInfo::getUserId, userId)
                .oneOpt().orElseThrow(() -> new NotFoundException("没有提交认证信息"));
    }

    @Override
    public EnterpriseCertInfoVo getEnterpriseCertInfoVoByUserId(Long userId) {
        QueryChain<EnterpriseCertInfo> queryChain = queryChain();
//        queryChain.select(ENTERPRISE_CERT_INFO.ALL_COLUMNS);
//        queryChain.leftJoin(ENTERPRISE_MANAGER.as("managers")).on(ENTERPRISE_MANAGER.as("managers").ENTERPRISE_CERT_INFO_ID.eq(ENTERPRISE_CERT_INFO.ID));
//        queryChain.leftJoin(ENTERPRISE_BENEFICIARY.as("beneficiaries")).on(ENTERPRISE_BENEFICIARY.as("beneficiaries").ENTERPRISE_CERT_INFO_ID.eq(ENTERPRISE_CERT_INFO.ID));
//        queryChain.select(ENTERPRISE_MANAGER.as("managers").ALL_COLUMNS);
//        queryChain.select(ENTERPRISE_BENEFICIARY.as("beneficiaries").ALL_COLUMNS);
        queryChain.eq(EnterpriseCertInfo::getUserId, userId);
        EnterpriseCertInfo enterpriseCertInfo = mapper.selectOneWithRelationsByQuery(queryChain);
        System.out.println("enterpriseCertInfo = " + enterpriseCertInfo);
        return BeanUtil.copyProperties(enterpriseCertInfo, EnterpriseCertInfoVo.class);

    }

    @Override
    public Boolean existsByUserId(Long userId) {
        return queryChain()
                .eq(EnterpriseCertInfo::getUserId, userId)
                .exists();
    }

    @Override
    public Page<EnterpriseCertInfoVo> paging(Page<EnterpriseCertInfo> pageable, Integer status, String certName, Long targetUserId) {
        QueryChain<EnterpriseCertInfo> queryChain = queryChain();
        queryChain.leftJoin(USER).on(USER.ID.eq(ENTERPRISE_CERT_INFO.USER_ID));
        queryChain.select(
                ENTERPRISE_CERT_INFO.ALL_COLUMNS,
                USER.EMAIL.as("account")
        );
        Long bossUserId = BossUserUtil.getIdNotNull();
        if (!BossUserUtil.hasAllData()) {
            queryChain.leftJoin(BOSS_USER.as("dealer")).on(USER.BE_LONG_TO_DEALER.eq(BOSS_USER.ID));
            queryChain.and(
                    BOSS_USER.as("dealer").ID.eq(bossUserId)
                            .or(BOSS_USER.as("dealer").PARENT_ID.eq(bossUserId))
            );
        }
        if (RegexUtil.checkObjectIsNotNull(status)) {
            queryChain.eq(EnterpriseCertInfo::getStatus, status);
        }
        if (RegexUtil.checkStringIsNotNull(certName)) {
            queryChain.like(EnterpriseCertInfo::getCompanyNameEn, certName);
        }
        if (RegexUtil.checkObjectIsNotNull(targetUserId)) {
            queryChain.eq(EnterpriseCertInfo::getUserId, targetUserId);
        }
        queryChain.orderBy(EnterpriseCertInfo::getRequestDate, false);
        Page<EnterpriseCertInfo> enterpriseCertInfoPage = mapper.paginateWithRelations(pageable, queryChain);
        return enterpriseCertInfoPage.map(
                enterpriseCertInfo ->
                        // 这里可以添加更多的处理逻辑，比如填充其他字段
                        BeanUtil.copyProperties(enterpriseCertInfo, EnterpriseCertInfoVo.class)
        );
    }

    @Override
    public Boolean audit(AuditKycDto auditKycDto) {
        EnterpriseCertInfo enterpriseCertInfo =
                queryChain().eq(EnterpriseCertInfo::getId, auditKycDto.getId())
                        .eq(EnterpriseCertInfo::getStatus, 2)
                        .eq(EnterpriseCertInfo::getStep, 6)
                        .oneOpt().orElseThrow(() -> new NotFoundException("认证信息不存在或已审核"));
        Long dealerId = userService.getDealerIdById(enterpriseCertInfo.getUserId());
        if (!BossUserUtil.hasAllData() && !dealerId.equals(BossUserUtil.getId())) {
            throw new ProgramException("无权操作用户的参数配置");
        }
        if (auditKycDto.getStatus()) {
            updateChain()
                    .eq(EnterpriseCertInfo::getId, auditKycDto.getId())
                    .set(EnterpriseCertInfo::getStatus, 0)
                    .set(EnterpriseCertInfo::getStep, 7)
                    .set(EnterpriseCertInfo::getAuditDate, new Date())
                    .set(EnterpriseCertInfo::getAuditUserId, dealerId)
                    .set(EnterpriseCertInfo::getAuditRemark, "审核通过:" + (RegexUtil.checkStringIsNull(auditKycDto.getRemark()) ? "" : auditKycDto.getRemark()))
                    .update();
        } else {
            updateChain()
                    .eq(EnterpriseCertInfo::getId, auditKycDto.getId())
                    .set(EnterpriseCertInfo::getStatus, 1)
                    .set(EnterpriseCertInfo::getStep, 7)
                    .set(EnterpriseCertInfo::getAuditDate, new Date())
                    .set(EnterpriseCertInfo::getAuditUserId, dealerId)
                    .set(EnterpriseCertInfo::getAuditRemark, "审核不通过:" + (RegexUtil.checkStringIsNull(auditKycDto.getRemark()) ? "" : auditKycDto.getRemark()))
                    .update();
        }
        return true;
    }

    @Override
    public Boolean removeByUserId(Long userId) {
        try {
            EnterpriseCertInfo enterpriseCertInfo = getByUserId(userId);
            if (enterpriseCertInfo.getStatus() == 0) {
                throw new ProgramException("认证已通过无法删除");
            }
            enterpriseManagerService.removeByEnterpriseCertInfoId(enterpriseCertInfo.getId());
            enterpriseBeneficiaryService.removeByEnterpriseCertInfoId(enterpriseCertInfo.getId());
            return removeById(enterpriseCertInfo.getId());
        } catch (NotFoundException e) {
            return true;
        }
    }
}
